<?php
namespace app\common\controller;
use think\Controller;
use lib\wechat\Wechat;
use lib\wechat\Map;
use think\facade\Cache;
use base\pay\WxApi;
use base\BaseMethod;

//定义公共控制器并继承核心框架的控制器
class WxService extends Controller
{
	
	/**
	* 微信配置
	* wx/wxConfig
	* 不需要登录 
	* @is_need_login false
	*/
    public function wxConfig() {
        //config("wechat.web")
        $config = env('system_base_config_wx_web');
        $weObj = new Wechat( $config );
        $weObj->valid();
        $getRev = $weObj->getRev()->getRevData();                                       //获取微信发来的消息对象
        $msgType =  $weObj->getRev()->getRevType();                                     //获取消息类型
        $result = $weObj->createMenu(["button" => $this->getMenu() ]);      //自定义菜单
        $errcode = json_decode($result,true)["errcode"];
        if($errcode=="42001") Cache::set('wechat_access_token'.$config['appid'],null);
		//$weObj->text( json_encode($getRev) )->reply(); 
	 	//回复  ↓
		switch($msgType) {
			case Wechat::MSGTYPE_TEXT://文本
					
				exit; break;
			case Wechat::MSGTYPE_IMAGE://图片消息
					
				exit; break;
			case Wechat::MSGTYPE_VOICE://音频消息
					
				exit; break;
			case Wechat::MSGTYPE_VIDEO://视频消息
					
				exit; break;
			case Wechat::MSGTYPE_MUSIC: //音乐消息
					
				exit; break;
			case Wechat::MSGTYPE_NEWS://图文消息
					
				exit; break;
			case Wechat::MSGTYPE_LINK://连接消息
					
				exit; break;		
			case "event"://事件消息。事件消息又分为下面五种
				//上报地址 - 添加地址
				if( $getRev['Event'] == 'LOCATION' ){
 					$this->addAppUserLocation($getRev);
				}
				//关注
				if( $getRev['Event'] == 'subscribe' ){
					$weObj->news( config("wechat.web.news") )->reply();	
				}
				//菜单点击事件
				if( $getRev['Event'] == 'CLICK' ){
					
				}
				exit; break;
		}
    }

	/**
	* 私有 ： 获取菜单
	* 不需要登录 
	* @is_need_login false
	*/
	private function getMenu(){
		$data = [];	
		try {
			$db=  \Db::table('xw_wechat_menu')->where('is_enable','启用')->order("sort_no")->select();
			foreach ($db as $key => $value) {
				if($value['pid']==0){
					$data[$key] = $this->getMenuArray($value);
					foreach ($db as $k => $val ) {
						if( $val['pid'] == $value['id'] ){
							$data[$key]['sub_button'][] = $this->getMenuArray($val);
						}
					}
				}
			}	
		} catch (\Exception $e) {
            
        }
		return empty($data) ? config("wechat.web.button") : $data;
    }
	//获取指定类型
	private function getMenuArray($arr){
		$data = [];
		switch ($arr['type']) {
			case 'view':
				$data = ['type'=> $arr['type'],'name'=> $arr['name'] , 'url'=> $arr['url'] ];
				break;
			case 'click':
				$data = [
					'type'=> $arr['type'], 
					'name'=> $arr['name'] , 
					'key'=> $arr['event_key'] ? $arr['event_key'] : 'MENU_KEY_NEWS'
				];
				break;
			case 'miniprogram':
				$data = [
					'type'=> $arr['type'],
					'name'=> $arr['name'] ,
					'url'=> $arr['url'], 
					'appid'=> $arr['appid'],
   					'pagepath'=> $arr['pagepath'] 
   				];
				break;	
			case '多级菜单类型':
				$data = ['name'=> $arr['name'] ];
				break;		
		}
		return $data;
	}
	
	/**
	* 私有 ： 记录上报的用户地理位置
	* 不需要登录 
	* @is_need_login false
	*/
	private function addAppUserLocation($getRev){
		$data = [
			'openid'=> $getRev['FromUserName'],
			'latitude'=> $getRev['Latitude'],
			'longitude'=> $getRev['Longitude'],
			'accuracy'=> $getRev['Precision'],
		];
		//转成火星坐标
		$mapresult = (new Map())->wgs84togcj02( $data['latitude'],$data['longitude']);
		$data['latitude'] = $mapresult[0];
		$data['longitude'] = $mapresult[1];
		//保存
		if( $data['openid'] && $data['latitude'] ){
			model("AppUserLocation")->where("openid", $data["openid"] )->delete();
			model("AppUserLocation")->allowField(true)->save($data);
		}
    }
	
    
    /**
    * 获取微信jsdk的签名
    * /wx/getSignPackage
    * 不需要登录 
    * @is_need_login false
    */
    public function getSignPackage() {
        $res = WxApi::getSignPackage();
        return BaseMethod::ReSucess($res);   
    }
    
    
}


